import axios from "axios";
import store from "../store";
import { ElMessage } from "element-plus";

const http = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

// 请求拦截
http.interceptors.request.use(
  (config) => {
    config.headers = {
      ...config.headers,
      Authorization: "Bearer" + store.state.user.token || "",
    };
    return config;
  },
  (err) => {
    Promise.reject(err);
  }
);

// 响应拦截
http.interceptors.response.use(
  (res) => {
    if (res.data.code === 0) {
      ElMessage({
        message: res.data.msg,
        type: "success",
      });
    } else {
      // console.log(res);
      ElMessage({
        message: res.data,
        type: "warning",
      });
    }
    return res.data;
  },
  (err) => {
    Promise.reject(err);
  }
);

export default http;
